package com.bw.config.security;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bw.entity.LoginUser;
import com.bw.entity.SysMenu;
import com.bw.entity.SysUser;
import com.bw.entity.SysUserRole;
import com.bw.mapper.SysUserMapper;
import com.bw.mapper.SysUserRoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 自定义用户
 */
@Component
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {


    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    SysUserRoleMapper  sysUserRoleMapper;

    /**
     * 从数据库中查询真实的用户
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        log.info("------loadUserByUsername is running-----");
        QueryWrapper queryWrapper = new QueryWrapper(); // 用来生成where条件
        queryWrapper.eq("user_name", username);
        SysUser sysUser = sysUserMapper.selectOne(queryWrapper);
        if (ObjectUtil.isNull(sysUser)) {
            log.info("登录用户：{} 不存在.", username);
            throw new UsernameNotFoundException("登录用户：" + username + " 不存在");
        }

        //权限 获取角色信息
          List<SysUserRole> roleList = sysUserRoleMapper.selectByUserId(sysUser.getId());
        List<String> authList = roleList.stream().map(SysUserRole::getRoleKey).collect(Collectors.toList());
       // List<String> authList = Arrays.asList("ROLE_ADMIN", "ROLE_USER");  //usersService.getAuth(sysUser.getId());//获取登录人的权限
//        List<MyGrantedAuthority> list = authList.stream().map(MyGrantedAuthority::new).collect(Collectors.toList());
//            List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList("ROLE_ADMIN", "ROLE_USER");
        //登录成功把用户的权限，存入redis
        //   redisTemplate.opsForValue().set("AUTH:" + username, list);

        //密码是否正确 交给springSecurity的去校验
        return new LoginUser(sysUser.getId(),username, sysUser.getPassword(),authList);

    }
}
